<template>
  <t-card :bordered="false">
    <!-- 顶部标签页 -->
    <t-tabs v-model:value="selectedTab" @change="handleGetCategory" v-if="list && list.length > 0">
      <template #action>
        <t-button theme="primary" variant="text" v-permission="['system:budget-model-sheet:create']" @click="handleOpenTopDialog('create', { modelId: props.modelId, contentType: props.contentType })">
          <template #icon><add-icon /></template>
          新建sheet
        </t-button>
      </template>
      <t-tab-panel v-for="item in list" :key="item.id" :value="item.id" :label="item.name">
        <template #label>
          {{ item.name }}
          <t-icon name="edit" v-permission="['system:budget-model-sheet:update']" @click="handleOpenTopDialog('update', { id: item.id })" />
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDeleteTop(item)">
            <t-icon name="delete" v-permission="['system:budget-model-sheet:delete']" />
          </t-popconfirm>
        </template>
      </t-tab-panel>
    </t-tabs>
    
    <!-- 空状态标签页 -->
    <t-tabs v-model:value="selectedTab" :list="hiddenList" @change="handleGetCategory" class="hidden" v-else>
      <template #action>
        <t-button theme="primary" variant="text" v-permission="['system:budget-model-sheet:create']" @click="handleOpenTopDialog('create', { modelId: props.modelId, contentType: props.contentType })">
          <template #icon><add-icon /></template>
          新建sheet
        </t-button>
      </template>
    </t-tabs>

    <!-- 主内容区域 -->
    <div class="container" v-if="list && list.length > 0">
      <!-- 左侧树形菜单 -->
      <t-space class="left" direction="vertical">
        <t-tree
          :data="categoryTree"
          activable
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          v-model:actived="actived"
          @click="handleClickCategoryTree"
        >
          <template #operations="{ node }">
            <t-space>
              <t-icon
                v-permission="['system:budget-model-space:update']"
                name="edit"
                @click="handleOpenLeftDialog('update', { id: node.data.id })"
              />
              <t-popconfirm content="确认要删除该项吗？" @confirm="handleDeleteLeft(node.data)">
                <t-icon v-permission="['system:budget-model-space:delete']" name="delete" />
              </t-popconfirm>
            </t-space>
          </template>
        </t-tree>
        <t-button
          block
          theme="primary" 
          variant="text"
          v-permission="['system:budget-model-space:create']"
          @click="handleOpenLeftDialog('create', { modelId: props.modelId, sheetId: selectedTab })"
        >
          <template #icon><add-icon /></template>
          新建空间
        </t-button>
      </t-space>
      
      <!-- 右侧内容区 -->
      <t-divider class="divider" layout="vertical" />
      <div v-show="searchParams.spaceId" class="right">
        <!-- 数据表格 -->
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columns"
          :api="budgetModelDataCRUD.page"
          :on-before-set-data="handleTableSetData"
          column-controller-key="ProgrammeList"
        >
          <template #topContent>
            <div style="display: flex;justify-content: space-between;">
              <t-button
                size="small"
                @click="handleOpenDialog('create', { spaceId: searchParams.spaceId })"
                v-permission="['system:budget-model-data:create']"
              >
                新建
              </t-button>
       
              <t-statistic  :value="statisticTotal" :decimal-places="2">
                <template #prefix>
                  总价：
                </template>
              </t-statistic>
                    
            </div>
          </template>
        
          <template #unit="{ row }">
            {{ dictionaryStore.analysis('unit', row.unit) }}
          </template>
          
          <template #operation="{ row }">
            <t-space break-line>
              <!-- <t-link theme="primary" @click="handleOpenDialog('read', { id: row.id })">
                详情
              </t-link> -->
              <t-link theme="primary"  @click="handleOpenDialog('update', { id: row.id })">
                编辑
              </t-link>
              <t-popconfirm  v-permission="['system:budget-model-data:update']" content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
                <t-link theme="danger" v-permission="['system:budget-model-data:delete']">删除</t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </custom-table>
      </div>
      <t-empty v-show="!searchParams.spaceId" class="right" title="请先选择项目" style="margin-top: 30vh" />
    </div>
   
    <!-- 项目编辑对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="budgetModelDataCRUD"
      header="*"
      :on-before-save-data="handleDialogSaveData"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <!-- 对话框表单内容 -->
      <t-form-item label="选项类型" name="projectType" :rules="[{ required: true, message: '请输入选项类型' }]">
        <t-radio-group v-model:value="formData.projectType" @change="handleProjectTypeChange">
          <t-radio
            v-for="_ in typeOption"
            :key="_.value"
            :value="_.value"
            
          >
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item v-if="['1'].includes(formData.projectType)" label="项目名称" name="name" :rules="[{ required: true, message: '请输入项目名称' }]">
        <t-button @click="visibleProgramme=true">选择项目</t-button>
        <t-input v-model:value="formData.name" readonly></t-input>
      </t-form-item>
      <t-form-item v-if="['2'].includes(formData.projectType)" label="主材名称" name="name" :rules="[{ required: true, message: '请输入主材名称' }]">
        <t-button @click="visibleMaterial=true">选择主材</t-button>
        <t-input v-model:value="formData.name" readonly></t-input>
      </t-form-item>
       <t-form-item v-if="['3'].includes(formData.projectType)" label="产品名称" name="name" :rules="[{ required: true, message: '请输入产品名称' }]">
        <t-button @click="visibleProduct=true">选择产品</t-button>
        <t-input v-model:value="formData.name" readonly></t-input>
      </t-form-item>
      <t-form-item label="数量" name="number" :rules="[{ required: true, message: '请输入数量' },{  min: 0, message: '数量不能小于0' }]">
        <t-input-number :decimal-places="2" :min="0" v-model:value="formData.number" placeholder="请输入数量" clearable :readonly="readonly" style="width: 100%;" />
      </t-form-item>
    
    </custom-dialog>
    
    <!-- 空间编辑对话框 -->
    <custom-dialog
      ref="customDialogLeftRef"
      v-slot="{ formData, readonly }"
      :api-map="budgeModelSpaceCRUD"
      header="*"
      @request-success="handleDialogRequestSuccessLeft"
    >
      <t-form-item label="空间名字" name="name" :rules="[{ required: true, message: '请输入空间名字' }]">
        <t-input v-model:value="formData.name" placeholder="请输入空间名字" clearable :readonly="readonly" />
      </t-form-item>
    </custom-dialog>
    
    <!-- Sheet编辑对话框 -->
    <custom-dialog
      ref="customDialogTopRef"
      v-slot="{ formData, readonly }"
      :api-map="budgeModelSheetCRUD"
      header="*"
      @request-success="handleDialogRequestSuccessTop"
    >
      <t-form-item label="sheet名称" name="name" :rules="[{ required: true, message: '请输入sheet名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入sheet名称" clearable :readonly="readonly" />
      </t-form-item>
    </custom-dialog>
      <!-- 选择项目对话框 -->
  <discuss-programme-selector-dialog 
    v-model:visible="visibleProgramme"
    :single="true"
    @save="handleSaveProgramme"
   />
     <!-- 主材 -->
    <cost-selection-dialog
      v-model:visible="visibleMaterial"
      :type="'1'"
      :single="true"
      @save="handleSaveMaterial"
     />
     <!-- 产品 -->
    <discuss-product-selector-dialog
      v-model:visible="visibleProduct"
      :order-id="null"
      :single="true"
      @save="handleSaveProduct" 
    />
  </t-card>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { AddIcon } from 'tdesign-icons-vue-next';

// API和组件导入
import { budgeModelSheetCRUD, budgeModelSpaceCRUD, budgetModelDataCRUD } from '@/api/budget/model'
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import Upload from '@/components/upload/index.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';
import DiscussProgrammeSelectorDialog from '@/pages/project/details/components/DiscussProgrammeSelectorDialog.vue';
import CostSelectionDialog from '@/pages/budget/programme/components/CostSelectionDialog.vue';
import DiscussProductSelectorDialog from '@/pages/project/details/components/DiscussProductSelectorDialog.vue';
// 组件属性定义
const props = defineProps({
  modelId: { type: Number, required: true }, // 模型ID
  contentType: { type: Number, required: true, default: 1 } // 内容类型
});
const emits = defineEmits(['refresh-subtotal']);
// 使用字典仓库
const dictionaryStore = useDictionaryStore();

// 响应式数据定义
const searchParams = reactive({ spaceId: null }); // 搜索参数
const selectedTab = ref(); // 当前选中的标签页
const list = ref([]); // sheet列表数据
const hiddenList = ref([{ label: '', value: '', destroyOnHide: true }]); // 隐藏的标签页列表
const categoryList = ref([]); // 空间列表数据
const categoryTree = ref([]); // 树形空间数据
const actived = ref([]); // 激活的树节点
const typeOption = [{label:'项目', value:'1'},{label:'主材', value:'2'},{label:'产品', value:'3'}]
// 表格列定义
const columns: TableCol[] = [
  { colKey: 'name', title: '项目名称', width: 180 },
  { colKey: 'unit', title: '单位', width:60 },
  { colKey: 'number', title: '数量' },
  { colKey: 'unitPrice', title: '单价(元)' },
  { colKey: 'totalPrice', title: '总价(元)' },
  { colKey: 'remark', title: '备注', width: 180 },
  { colKey: 'operation', title: '操作', fixed: 'right',width:100 },
];

// 组件引用
const customTableRef = ref(); // 表格组件引用
const customDialogRef = ref(); // 项目对话框引用
const customDialogLeftRef = ref(); // 空间对话框引用
const customDialogTopRef = ref(); // sheet对话框引用
// 选择项目
const visibleProgramme = ref(false)
// 选择产品
const visibleProduct = ref(false)
// 选择主材
const visibleMaterial = ref(false)
// 总价
const statisticTotal = ref(0)
/**
 * 初始化数据
 */
const initData = async () => {
  try {
    const params = { modelId: props.modelId, contentType: props.contentType };
    const sheetList = await budgeModelSheetCRUD.page(params);
 
    
    if (sheetList?.length > 0) {
      list.value = sheetList;
      selectedTab.value = list.value[0].id;
      await handleGetCategory();
    } else {
      list.value = []
    }
  } catch ({ message }) {
    MessagePlugin.error(message);
  }
};

/**
 * 获取空间分类数据
 */
const handleGetCategory = async () => {
  if (!selectedTab.value) return;
  
  const params = { pageSize: -1, sheetId: selectedTab.value };
  
  try {
    const { list: spaceList } = await budgeModelSpaceCRUD.page(params);
    categoryList.value = spaceList;
    categoryTree.value = listToTree(spaceList);
    
    if (categoryTree.value.length > 0) {
      actived.value = [categoryTree.value[0].id];
      searchParams.spaceId = categoryTree.value[0].id;
      handleInitTable();
    } else {
      searchParams.spaceId = null;
    }
  } catch ({ message }) {
    MessagePlugin.error(message);
  }
};

/**
 * 初始化表格数据
 */
const handleInitTable = () => {
  if (!customTableRef.value) return;
  customTableRef.value.initTable({ spaceId: searchParams.spaceId });
};

/**
 * 刷新表格数据
 */
const handleRefreshTable = () => {
  if (!customTableRef.value) return;
  customTableRef.value.refreshTable();
};
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  statisticTotal.value = data.totalPrice?data.totalPrice:0
  return data.list;
};
/**
 * 点击树节点事件
 */
const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  searchParams.spaceId = node.value;
  handleInitTable();
};

/**
 * 获取sheet列表
 */
const handleGetSheet = async () => {
  try {
    const params = { modelId: props.modelId, contentType: props.contentType };
    const sheetList  = await budgeModelSheetCRUD.page(params);
    console.log(sheetList,'sheetList');
    
    list.value = sheetList || [];
  } catch ({ message }) {
    MessagePlugin.error(message);
  }
};

// 对话框操作相关方法
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => customDialogRef.value?.open(mode, params);
const handleOpenLeftDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => customDialogLeftRef.value?.open(mode, params);
const handleOpenTopDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => customDialogTopRef.value?.open(mode, params);

// 对话框回调方法
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
  emits('refresh-subtotal');
};
const handleDialogRequestSuccessLeft = () => handleGetCategory();
const handleDialogRequestSuccessTop = async () => {
  await handleGetSheet();
  if (list.value.length > 0) {
    selectedTab.value = list.value[0].id;
    await handleGetCategory();
  }
};

// 删除相关方法
const handleDelete = async (params: Record<string, any>) => {
  try {
    await budgetModelDataCRUD.delete(params);
    MessagePlugin.success('删除成功');
    handleRefreshTable();
    emits('refresh-subtotal');
  } catch ({ message }) {
    MessagePlugin.error(message);
  }
};

const handleDeleteLeft = async (params: Record<string, any>) => {
  try {
    await budgeModelSpaceCRUD.delete(params);
    MessagePlugin.success('删除成功'); 
    await handleGetCategory();
    searchParams.spaceId = null;
  } catch ({ message }) {
    MessagePlugin.error(message);
  }
};

const handleDeleteTop = async (params: Record<string, any>) => {
  try {
    await budgeModelSheetCRUD.delete(params);
    MessagePlugin.success('删除成功'); 
    await handleGetSheet();
    searchParams.spaceId = null;
  } catch ({ message }) {
    MessagePlugin.error(message);
  }
};

// 对话框数据处理方法
const handleDialogSetData = (params: Record<string, any>) => {

};

const handleDialogSaveData = (params: Record<string, any>) => {
  
};
// 处理保存项目数据方法
const handleSaveProgramme = (selectedData: any[]) => {
  customDialogRef.value.formData.name = selectedData[0].name
  // customDialogRef.value.formData.imgUrl = selectedData[0].fileUrl
  customDialogRef.value.formData.unit = selectedData[0].unit
  customDialogRef.value.formData.unitPrice = selectedData[0].unitPrice
  customDialogRef.value.formData.projectId = selectedData[0].projectId
  customDialogRef.value.formData.remark = selectedData[0].remark
  
}
// 处理保存主材数据方法
const handleSaveMaterial = (selectedData: any[]) => {

  customDialogRef.value.formData.name = selectedData[0].name
  // customDialogRef.value.formData.imgUrl = selectedData[0].fileUrl
  customDialogRef.value.formData.unit = selectedData[0].unit
  customDialogRef.value.formData.unitPrice = selectedData[0].sellingPrice
  customDialogRef.value.formData.projectId = selectedData[0].materialId
  customDialogRef.value.formData.remark = selectedData[0].remark
}
// 处理保存产品数据方法
const handleSaveProduct= (selectedData: any[]) => {
  customDialogRef.value.formData.name = selectedData[0].name
  // customDialogRef.value.formData.imgUrl = selectedData[0].fileUrl
  customDialogRef.value.formData.unit = selectedData[0].unit
  customDialogRef.value.formData.unitPrice = selectedData[0].unitPrice
  customDialogRef.value.formData.projectId = selectedData[0].productId
  customDialogRef.value.formData.remark = selectedData[0].remark
}
// 处理选项类型切换的时候
const handleProjectTypeChange = () => {
  customDialogRef.value.formData.name = ''
  customDialogRef.value.formData.unit = ''
  customDialogRef.value.formData.unitPrice = ''
  customDialogRef.value.formData.projectId = ''
  customDialogRef.value.formData.remark = ''
}
// 监听props变化
watch(
  () => [props.contentType, props.modelId], 
  () => initData(), 
  { immediate: true }
);

// 组件挂载时初始化
onMounted(initData);
</script>

<style lang="less" scoped>
/* 容器样式 */
.container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  margin-top: 10px;

  /* 左侧树样式 - 改为自适应高度 */
  .left {
    width: 200px;
    overflow: hidden; /* 保留溢出隐藏 */

    :deep(.t-tree) {
      padding-right: 8px;
      max-height: none; /* 移除最大高度限制 */
      height: auto; /* 高度由内容决定 */

      /* 保留滚动条样式 */
      &::-webkit-scrollbar {
        width: 8px;
        background: transparent;
      }
      &::-webkit-scrollbar-thumb {
        border-radius: 6px;
        border: 2px solid transparent;
        background-clip: content-box;
        background-color: var(--td-scrollbar-color);
      }
    }
  }

  /* 分隔线样式 - 改为自适应高度 */
  .divider {
    height: auto;
    align-self: stretch; /* 使分隔线与内容同高 */
  }

  /* 右侧内容区 */
  .right {
    width: calc(100% - 225px);
    min-height: 200px; /* 保留最小高度保证显示 */
  }
}

/* 标签页操作按钮样式 */
:deep(.t-tabs__operations--right) {
  top: 15px;
}

/* 隐藏标签页文字样式 */
:deep(.hidden .t-tabs__nav-item-text-wrapper) {
  visibility: hidden;
}
:deep(.t-statistic-content-prefix) {
  font-size: 14px;
}
:deep(.t-statistic-content-value) {
  font-size: 18px;
}
</style>